package com.biqee.service.user.impl;

import java.util.List;

import org.apache.log4j.Logger;

import com.biqee.framework.context.RequestContext;
import com.biqee.model.db.BqUser;
import com.biqee.model.db.UserVersion;
import com.biqee.service.db.BqUserService;
import com.biqee.service.db.UserVersionService;
import com.biqee.service.user.LoginService;
import com.biqee.util.PasswordUtil;
import com.biqee.util.StringUtil;

public class LoginServiceImpl implements LoginService {
	private static final Logger logger = Logger.getLogger(LoginServiceImpl.class);
	
	/**
	 * 注意，如果有验证码，请不要在这里验证，需要另写验证码验证Service，并在LoginAction中调用
	 * 验证码验证通过后才调用本方法
	 * 
	 * @param loginName
	 * @param password
	 * @return
	 */
	@Override
	public boolean checkLogin(String loginName, String password) {
		BqUser bqUser = bqUserService.readByLoginName(loginName);
		if(bqUser == null) {
			logger.warn("no match loginName for " + loginName);
			return false;
		}
		
		String passwordEncrpted = PasswordUtil.encryptedByMD5(password);
		if(StringUtil.equals(passwordEncrpted, bqUser.getPassword())) {
			logger.warn("password not match. loginName: " + loginName + ", password: " + password);
			return false;
		}

		return true;
	}
	
	@Override
	public void login(String loginName) {
		BqUser bqUser = bqUserService.readByLoginName(loginName);
		login(bqUser);
	}
	
	@Override
	public void login(Long bqUserId) {
		BqUser bqUser = bqUserService.readById(bqUserId);
		login(bqUser);
	}

	private void login(BqUser bqUser) {
		if(bqUser == null) {
			return;
		}
		
		logger.info("user login. userId: " + bqUser.getId());
		
		// put user info into the request context
		RequestContext.setUser(bqUser);
		List<UserVersion> userVersions = userVersionService.readByBqUserId(bqUser.getId());
		RequestContext.setUserVersions(userVersions);
	}
	
	private BqUserService bqUserService;

	public void setBqUserService(BqUserService bqUserService) {
		this.bqUserService = bqUserService;
	}
	
	private UserVersionService userVersionService;

	public void setUserVersionService(UserVersionService userVersionService) {
		this.userVersionService = userVersionService;
	}
	
}
